from django.shortcuts import render_to_response,redirect
from django.http import HttpResponse

#from google.appengine.api import search
#from google.appengine.api.search import search
from google.appengine.api.search.search import Document,TextField,DateField
from google.appengine.api.search.search import Index
from datetime import datetime

import logging
import traceback

from jieba import finalseg 

_LYRIC_INDEX_NAME = 'lyrics'

def add_lyric(request):
    """
    if get request, return the page
    elif post request, return the status
    """
    if request.method == "GET":
        return render_to_response('search/add_search_lyric.html')

    elif request.method == "POST":
        lyric_str = request.POST['lyric_str']
        try:
            ws = finalseg.cut(lyric_str)
            seg_lyric_str = ""
            for w in ws:
                seg_lyric_str += w + ' '
        except:
            return HttpResponse(traceback.format_exc())

        d = Document(
                fields=[
                    TextField(name='lyric',value=lyric_str),
                    TextField(name='seg_lyric',value=seg_lyric_str),
                    DateField(name='date',value=datetime.now().date())
                    ])

        try:
            Index(name=_LYRIC_INDEX_NAME).put(d)
        except search.Error:
            logging.exception('put to index failed')

        return HttpResponse('<a href="/s/add_lyric">add new</a>')
    else:
        pass

def search(request):
    if request.method == "GET":
        return render_to_response('search/search_page.html')

    elif request.method == "POST":
        w = request.POST['w']
        try:
            results = Index(name=_LYRIC_INDEX_NAME).search(w)
            lrc_list = []
            for l_doc in results:
                # get the results
                lrc_dic = {}
                lrc_dic['str'] = l_doc.fields[0].value
                lrc_dic['date'] = str(l_doc.fields[2].value)
                lrc_list.append(lrc_dic)
                logging.error(str(len(lrc_list)))
            dic = {}
            if len(lrc_list) != 0:
                dic['lrc_list'] = lrc_list
            return render_to_response('search/search_page.html',dic)

        except search.Error:
            logging.exception('Search Failed')
    else:
        pass


def seg_sentence(request):
    """
    this is for test only, will be removed later
    try the jieba module
    """
    if request.method == "GET":
        return render_to_response('search/seg_sentence.html')
    elif request.method == "POST":
        sen = request.POST['sen']
        ws = finalseg.cut(sen)
        dic = {}
        dic['sen'] = sen
        dic['ws'] = ws
        return render_to_response('search/seg_sentence.html',dic)
    else:
        pass

